package com.zjy.financialsystemjavafx.controller;

import com.zjy.financialsystemjavafx.model.entity.Account;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import java.io.IOException;
import com.zjy.financialsystemjavafx.service.AccountService;
import com.zjy.financialsystemjavafx.util.SessionContext;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.ChoiceDialog;
import java.util.Optional;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Arrays;

/**
 * 账户管理控制器
 */
public class AccountController {

    @FXML
    private TableView<Account> accountTable;

    @FXML
    private TableColumn<Account, Integer> idColumn;

    @FXML
    private TableColumn<Account, String> nameColumn;

    @FXML
    private TableColumn<Account, String> typeColumn;

    @FXML
    private TableColumn<Account, Double> balanceColumn;

    @FXML
    private TableColumn<Account, String> descColumn;

    @FXML
    private Button addButton;

    @FXML
    private Button editButton;

    @FXML
    private Button deleteButton;

    @FXML
    private Button transferButton;

    @FXML
    private Button backButton;

    private ObservableList<Account> accountList = FXCollections.observableArrayList();
    private AccountService accountService;
    private int userId;

    @FXML
    private void initialize() {
        // 初始化服务和用户ID
        accountService = new AccountService();
        userId = SessionContext.getCurrentUser().getUserId();

        // 配置列
        idColumn.setCellValueFactory(new PropertyValueFactory<>("accountId"));
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("accountName"));
        typeColumn.setCellValueFactory(new PropertyValueFactory<>("accountType"));
        balanceColumn.setCellValueFactory(new PropertyValueFactory<>("currentBalance"));
        descColumn.setCellValueFactory(new PropertyValueFactory<>("description"));

        // 绑定数据列表到表格
        accountTable.setItems(accountList);

        // 刷新表格数据
        refreshTable();
    }

    /**
     * 从数据库加载账户并刷新表格
     */
    private void refreshTable() {
        try {
            accountList.clear();
            accountList.addAll(accountService.getAccounts(userId));
            System.out.println("[DEBUG] Loaded accounts count: " + accountList.size());
            accountTable.setItems(accountList);
        } catch (Exception e) {
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载账户数据: " + e.getMessage());
            alert.showAndWait();
        }
    }

    @FXML
    private void handleAdd(ActionEvent event) {
        // 弹出对话框依次收集账户信息
        TextInputDialog nameDialog = new TextInputDialog();
        nameDialog.setTitle("添加账户");
        nameDialog.setHeaderText(null);
        nameDialog.setContentText("请输入账户名称：");
        Optional<String> nameOpt = nameDialog.showAndWait();
        if (!nameOpt.isPresent()) return;
        String name = nameOpt.get();

        TextInputDialog typeDialog = new TextInputDialog();
        typeDialog.setTitle("添加账户");
        typeDialog.setHeaderText(null);
        typeDialog.setContentText("请输入账户类型：");
        Optional<String> typeOpt = typeDialog.showAndWait();
        if (!typeOpt.isPresent()) return;
        String type = typeOpt.get();

        TextInputDialog balDialog = new TextInputDialog("0.0");
        balDialog.setTitle("添加账户");
        balDialog.setHeaderText(null);
        balDialog.setContentText("请输入初始余额：");
        Optional<String> balOpt = balDialog.showAndWait();
        if (!balOpt.isPresent()) return;
        double initBalance;
        try {
            initBalance = Double.parseDouble(balOpt.get());
        } catch (NumberFormatException ex) {
            return;
        }

        TextInputDialog descDialog = new TextInputDialog();
        descDialog.setTitle("添加账户");
        descDialog.setHeaderText(null);
        descDialog.setContentText("请输入描述：");
        Optional<String> descOpt = descDialog.showAndWait();
        String desc = descOpt.orElse("");

        try {
            boolean ok = accountService.addAccount(userId, name, type, initBalance, desc);
            if (ok) refreshTable();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleEdit(ActionEvent event) {
        Account selected = accountTable.getSelectionModel().getSelectedItem();
        if (selected == null) {
            showSelectWarning();
            return;
        }
        // 弹出对话框依次编辑账户信息
        TextInputDialog nameDialog = new TextInputDialog(selected.getAccountName());
        nameDialog.setTitle("编辑账户");
        nameDialog.setHeaderText(null);
        nameDialog.setContentText("账户名称：");
        Optional<String> nameOpt2 = nameDialog.showAndWait();
        if (!nameOpt2.isPresent()) return;
        selected.setAccountName(nameOpt2.get());

        TextInputDialog typeDialog2 = new TextInputDialog(selected.getAccountType());
        typeDialog2.setTitle("编辑账户");
        typeDialog2.setHeaderText(null);
        typeDialog2.setContentText("账户类型：");
        Optional<String> typeOpt2 = typeDialog2.showAndWait();
        if (!typeOpt2.isPresent()) return;
        selected.setAccountType(typeOpt2.get());

        TextInputDialog balDialog2 = new TextInputDialog(String.valueOf(selected.getCurrentBalance()));
        balDialog2.setTitle("编辑账户");
        balDialog2.setHeaderText(null);
        balDialog2.setContentText("当前余额：");
        Optional<String> balOpt2 = balDialog2.showAndWait();
        if (!balOpt2.isPresent()) return;
        try {
            selected.setCurrentBalance(Double.parseDouble(balOpt2.get()));
        } catch (NumberFormatException ex) {
            return;
        }

        TextInputDialog descDialog2 = new TextInputDialog(selected.getDescription());
        descDialog2.setTitle("编辑账户");
        descDialog2.setHeaderText(null);
        descDialog2.setContentText("描述：");
        Optional<String> descOpt2 = descDialog2.showAndWait();
        selected.setDescription(descOpt2.orElse(""));

        try {
            boolean ok = accountService.updateAccount(selected);
            if (ok) refreshTable();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleDelete(ActionEvent event) {
        Account selected = accountTable.getSelectionModel().getSelectedItem();
        if (selected == null) {
            showSelectWarning();
            return;
        }
        try {
            boolean ok = accountService.deleteAccount(selected.getAccountId());
            if (ok) refreshTable();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleTransfer(ActionEvent event) {
        try {
            // 获取账户列表
            List<Account> accounts = accountService.getAccounts(userId);
            if (accounts.size() < 2) {
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setTitle("转账");
                alert.setHeaderText(null);
                alert.setContentText("至少需要两个账户才能进行转账");
                alert.showAndWait();
                return;
            }
            // 选择转出账户
            ChoiceDialog<String> fromDialog = new ChoiceDialog<>(accounts.get(0).getAccountName(),
                    accounts.stream().map(Account::getAccountName).collect(Collectors.toList()));
            fromDialog.setTitle("转账");
            fromDialog.setHeaderText(null);
            fromDialog.setContentText("请选择转出账户：");
            Optional<String> fromOpt = fromDialog.showAndWait();
            if (!fromOpt.isPresent()) return;
            String fromName = fromOpt.get();
            int fromId = accounts.stream().filter(a -> a.getAccountName().equals(fromName))
                    .findFirst().orElse(accounts.get(0)).getAccountId();
            // 选择转入账户
            List<Account> destAccounts = accounts.stream()
                    .filter(a -> !a.getAccountName().equals(fromName))
                    .collect(Collectors.toList());
            ChoiceDialog<String> toDialog = new ChoiceDialog<>(destAccounts.get(0).getAccountName(),
                    destAccounts.stream().map(Account::getAccountName).collect(Collectors.toList()));
            toDialog.setTitle("转账");
            toDialog.setHeaderText(null);
            toDialog.setContentText("请选择转入账户：");
            Optional<String> toOpt = toDialog.showAndWait();
            if (!toOpt.isPresent()) return;
            String toName = toOpt.get();
            int toId = destAccounts.stream().filter(a -> a.getAccountName().equals(toName))
                    .findFirst().orElse(destAccounts.get(0)).getAccountId();
            // 输入金额
            TextInputDialog amtDialog = new TextInputDialog();
            amtDialog.setTitle("转账");
            amtDialog.setHeaderText(null);
            amtDialog.setContentText("请输入转账金额：");
            Optional<String> amtOpt = amtDialog.showAndWait();
            if (!amtOpt.isPresent()) return;
            double amount = Double.parseDouble(amtOpt.get());
            if (amount <= 0) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("转账");
                alert.setHeaderText(null);
                alert.setContentText("转账金额必须大于 0");
                alert.showAndWait();
                return;
            }
            // 执行转账
            boolean ok = accountService.transfer(fromId, toId, amount);
            Alert alert = new Alert(ok ? Alert.AlertType.INFORMATION : Alert.AlertType.ERROR);
            alert.setTitle("转账");
            alert.setHeaderText(null);
            alert.setContentText(ok ? "转账成功" : "转账失败");
            alert.showAndWait();
            if (ok) refreshTable();
        } catch (Exception e) {
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("转账错误");
            alert.setHeaderText(null);
            alert.setContentText("转账过程中出现错误: " + e.getMessage());
            alert.showAndWait();
        }
    }

    /**
     * 返回仪表盘视图
     */
    @FXML
    private void handleBack(ActionEvent event) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/com/zjy/financialsystemjavafx/view/Dashboard.fxml"));
            Stage stage = (Stage) accountTable.getScene().getWindow();
            stage.setTitle("个人财务管家 - 仪表盘");
            stage.setScene(new Scene(root));
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载仪表盘界面");
            alert.showAndWait();
        }
    }

    private void showSelectWarning() {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle("未选择");
        alert.setHeaderText(null);
        alert.setContentText("请先选择一条账户记录");
        alert.showAndWait();
    }
} 